<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户名称" prop="userName">
        <el-input v-model="queryParams.userName" placeholder="请输入用户名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="积分总数" prop="points">
        <el-input v-model="queryParams.points" placeholder="请输入积分总数" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- 积分总数新增功能已隐藏 -->
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['points:profile:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['points:profile:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['points:profile:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="profileList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键ID" align="center" prop="id" />
      <el-table-column label="用户名称" align="center" prop="sysYouYouUser.userName">
        <template slot-scope="scope">
          {{ scope.row.sysYouYouUser && scope.row.sysYouYouUser.userName ? scope.row.sysYouYouUser.userName : '' }}
        </template>
      </el-table-column>
      <el-table-column label="会员类型" align="center" prop="memberType">
        <template slot-scope="scope">

          <span v-if="scope.row.memberType === 1 || scope.row.memberType === '1' || scope.row.memberType === 'NONE'">非会员</span>
          <span v-else-if="scope.row.memberType === 2 || scope.row.memberType === '2' || scope.row.memberType === 'EXCLUSIVE'">{{ '普通会员' }}</span>
          <span v-else-if="scope.row.memberType === 3 || scope.row.memberType === '3' || scope.row.memberType === 'GLOBAL'">{{ '全站会员' }}</span>
          <span v-else-if="!scope.row.memberType">未设置</span>
          <span v-else>未知类型 (值: {{ scope.row.memberType }})</span>
        </template>
      </el-table-column>
      <el-table-column label="积分总数" align="center" prop="points" />

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['points:profile:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['points:profile:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改积分总数对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

        <el-form-item label="积分总数" prop="points">
          <el-input v-model="form.points" placeholder="请输入积分总数" />
        </el-form-item>
        <el-form-item label="会员类型" prop="memberType">
          <el-select v-model="form.memberType" placeholder="请选择会员类型">
            <el-option label="非会员" value="1"></el-option>
            <el-option label="普通会员 " value="2"></el-option>
            <el-option label="全站会员 " value="3"></el-option>
          </el-select>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProfile, getProfile, delProfile, addProfile, updateProfile, userWithProfile } from "@/api/points/profile"

function validateUserId(rule, value, callback) {
  if (value === null || value === undefined || value === '') {
    callback(new Error('关联的用户ID不能为空'));
  } else {
    callback();
  }
}

export default {
  name: "Profile",
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      profileList: [],
      title: "",
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: null,
        memberType: null,
        points: null
      },
      form: {},
      rules: {
        userId: [
          { required: true, validator: validateUserId, trigger: "blur" }
        ],
        memberType: [
          { required: true, message: '请选择会员类型', trigger: "change" },
          {
            validator: (rule, value, callback) => {

              if ([1, 2, 3, '1', '2', '3', 'NONE', 'EXCLUSIVE', 'GLOBAL'].includes(value)) {
                callback();
              } else {
                callback(new Error('会员类型必须是0、1、2或NONE、EXCLUSIVE、GLOBAL'));
              }
            },
            trigger: "change"
          }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
        async getList() {
      this.loading = true;
      try {
        // 创建查询参数的副本
        const params = { ...this.queryParams };
        
        // 使用userWithProfile接口，支持用户名联查
        const response = await userWithProfile(params);
        
        // 确保数据格式一致
        this.profileList = response.rows || response.data || [];
        this.total = response.total || this.profileList.length;
        
        console.log("response data:", response);
        console.log("profileList:", this.profileList);
      } catch (error) {
        console.error("查询接口调用失败:", error);
        this.profileList = [];
        this.total = 0;
        this.$message.error("查询接口异常，请重试");
      } finally {
        this.loading = false;
      }
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
        this.form = {
          id: null,
          userId: null,
          userName: null,
          memberType: null,
          memberExpire: null,
          points: null,
          practiceCount: null
        };
      this.resetForm("form");
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加积分总数";
    },
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getProfile(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改积分总数";
      });
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateProfile(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProfile(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除积分总数编号为"' + ids + '"的数据项？').then(function() {
        return delProfile(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    handleExport() {
      this.download('points/profile/export', {...this.queryParams}, `profile_${new Date().getTime()}.xlsx`);
    }
  }
};
</script>
